package com.hyk.interceptor;


import com.hyk.enums.ApiEnum;
import com.hyk.exception.GlobalException;
import com.hyk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;

/**
 * @Author: hyk
 * @Date: 2021/3/23 9:38 AM
 * @Version 1.0
 */
@Component
public class JwtFilter implements HandlerInterceptor {

    private static final String noTokne = "/user/login,/user/verificationCode,/user/register,/doc.html,/error," +
            "/webjars/bycdao-ui/images/api.ico,/swagger-resources,/webjars/bycdao-ui/ace-editor/theme-eclipse.js," +
            "/webjars/bycdao-ui/ace-editor/mode-json.js";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if(request.getMethod().equalsIgnoreCase("OPTIONS") ||
        request.getMethod().equalsIgnoreCase("GET")){
            return true;
        }

        String admin = request.getHeader("admin");
        if (admin != null){
            return true;
        }

        //排除不需要token接口
        String servletPath = request.getServletPath();
        System.out.println("servletPath = " + servletPath);
        for(String string : noTokne.split(",")){
            if(servletPath.equals(string)){
                return true;
            }
        }
        String token = request.getHeader(JwtUtils.TOKEN_HEADER);

        if(StringUtils.isBlank(token)){
            throw new GlobalException(ApiEnum.TOKEN_IS_ILLEGAL);
        }
        Claims claims = JwtUtils.parseJWT(token);
        LinkedHashMap user = claims.get("user", LinkedHashMap.class);
        request.setAttribute("user",user);
        return true;
    }
}